<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020/9/21 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */
namespace common\models;

use Yii;
use yii\base\Model;
use yii\web\UploadedFile;

/**
 * Oauth bind form
 */
class OauthBindForm extends BaseModel
{
    public $account;
    public $nickname;
    public $type; // 第三方类型：weixin微信 alipay支付宝
    public $sex = -1; //性别
    public $openid = '';
    public $unionid;
    public $avatar;

    private $_oauth = null;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['account', 'nickname', 'type', 'openid', 'unionid', 'avatar'], 'trim'],
            [['account', 'nickname', 'type', 'unionid'], 'required'],
        ];
    }

    /**
     * 验证是否已绑定
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateOauth()
    {
        if ($this->type == 'weixin' && !$this->hasErrors()) {
            $this->_oauth = UserOauth::find()->where(['unionid' => $this->unionid, 'oauth_type' => UserOauth::OAUTH_TYPE_WEIXIN])->one();
            if ($this->_oauth && $this->_oauth->uid > 0) {
                $this->addError('uid', '此微信号已绑定过了，请解绑后再操作');
                return false;
            }
            if (empty($this->_oauth)) {
                $this->_oauth = new UserOauth();
            }
        } else if ($this->type == 'alipay' && !$this->hasErrors()) {
            $this->_oauth = UserOauth::find()->where(['unionid' => $this->unionid, 'oauth_type' => UserOauth::OAUTH_TYPE_ALIPAY])->one();
            if ($this->_oauth && $this->_oauth->uid > 0) {
                $this->addError('uid', '此支付宝已绑定过了，请解绑后再操作');
                return false;
            }
            if (empty($this->_oauth)) {
                $this->_oauth = new UserOauth();
            }
        }
        return true;
    }

    /**
     * 绑定支付宝
     * @return bool
     */
    public function bindAlipay()
    {
        try {
            if ($this->validate() && $this->validateOauth()) {
                $this->_oauth->uid = Yii::$app->getUser()->getId();
                $this->_oauth->account = $this->account;
                $this->_oauth->nickname = $this->nickname;
                $this->_oauth->openid = $this->openid;
                $this->_oauth->unionid = $this->unionid;
                $this->_oauth->oauth_type = UserOauth::OAUTH_TYPE_ALIPAY;
                $this->_oauth->sex = $this->sex == 1 ? 1 : ($this->sex == 0 ? 0 : -1);
                $this->_oauth->avatar = $this->_uploadAvatar($this->avatar);
                $this->_oauth->created_at = $this->_oauth->updated_at = date('Y-m-d H:i:s');
                if ($this->_oauth->save(false)) {
                    $user = Yii::$app->getUser()->getIdentity();
                    $user->updateAvatar($this->_oauth->avatar);
                    return true;
                }
            }
        } catch (\Exception $e) {
            $this->addError('unionid', $e->getMessage());
        }
        return false;
    }

    /**
     * 绑定微信
     * @return bool
     */
    public function bindWeixin()
    {
        try {
            if ($this->validate() && $this->validateOauth()) {
                $this->_oauth->uid = Yii::$app->getUser()->getId();
                $this->_oauth->account = $this->account;
                $this->_oauth->nickname = $this->nickname;
                $this->_oauth->openid = $this->openid;
                $this->_oauth->unionid = $this->unionid;
                $this->_oauth->oauth_type = UserOauth::OAUTH_TYPE_WEIXIN;
                $this->_oauth->sex = $this->sex == 1 ? 1 : ($this->sex == 0 ? 0 : -1);
                $this->_oauth->avatar = $this->_uploadAvatar($this->avatar);
                $this->_oauth->created_at = $this->_oauth->updated_at = date('Y-m-d H:i:s');
                if ($this->_oauth->save(false)) {
                    $user = Yii::$app->getUser()->getIdentity();
                    $user->updateAvatar($this->_oauth->avatar);
                    return true;
                }
            }
        } catch (\Exception $e) {
            $this->addError('unionid', $e->getMessage());
        }
        return false;
    }
    /**
     * 解绑支付宝
     * @return bool
     */
    public static function unbindAlipay($uid)
    {
        if ($model = UserOauth::findOne(['uid' => $uid, 'oauth_type' => UserOauth::OAUTH_TYPE_ALIPAY])) {
            $model->uid = 0;
            $model->updated_at = date('Y-m-d H:i:s');
            return $model->update(false, ['uid', 'updated_at']);
        }
        return false;
    }

    /**
     * 解绑微信
     * @return bool
     */
    public static function unbindWeixin($uid)
    {
        if ($model = UserOauth::findOne(['uid' => $uid, 'oauth_type' => UserOauth::OAUTH_TYPE_WEIXIN])) {
            $model->uid = 0;
            $model->updated_at = date('Y-m-d H:i:s');
            return $model->update(false, ['uid', 'updated_at']);
        }
        return false;
    }

    /**
     * 上传头像
     * @param $img 头像
     */
    private function _uploadAvatar($img)
    {
        if ($data = Yii::$app->util->curlGetImage($img)) {
            $temp = tempnam(sys_get_temp_dir(), 'oauthavatar');
            file_put_contents($temp, $data);
            $info = pathinfo($img);
            $_FILES['imageFile']['name'] = $info['basename'];
            $_FILES['imageFile']['type'] = mime_content_type($temp);
            $_FILES['imageFile']['size'] = filesize($temp);
            $_FILES['imageFile']['tmp_name'] = $temp;
            $_FILES['imageFile']['error'] = UPLOAD_ERR_OK;
            $model = new UploadForm(['scenario' => 'image']);
            $model->imageFile = UploadedFile::getInstanceByName('imageFile');
            if ($res = $model->uploadOauthAvatar(Yii::$app->user->getId())) {
                return $res['url'];
            }
        }
        return $img;
    }
}
